//
//  WebNotifier.m
//  Cidney
//
//  Created by Chris Karr on 1/19/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "WebNotifier.h"
#import "Dispatcher.h"
#import <AddressBook/AddressBook.h>

#define CIDNEY_WEB_UPDATE @"Cidney Web Update"
#define CIDNEY_WEB_UPDATE_URL @"Cidney Web Update URL"
#define CIDNEY_WEB_UPDATE_USER @"Cidney Web Update Username"
#define CIDNEY_WEB_UPDATE_PASS @"Cidney Web Update Password"

@implementation WebNotifier

@synthesize lastCall;
@synthesize uploadTimer;

- (void) awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:INCOMING_CALL object:nil];
}

- (void) update: (NSNotification *) msg
{
	self.lastCall = [msg userInfo];
	
	if (self.uploadTimer != nil)
		[self.uploadTimer invalidate];

	if ([[NSUserDefaults standardUserDefaults] boolForKey:CIDNEY_WEB_UPDATE])
		self.uploadTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(upload:) userInfo:nil repeats:NO];
}

- (void) upload:(NSTimer *) theTimer
{
	NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
	
	NSString * urlBase = [defaults stringForKey:CIDNEY_WEB_UPDATE_URL];
	NSString * user = [defaults stringForKey:CIDNEY_WEB_UPDATE_USER];
	NSString * pass = [defaults stringForKey:CIDNEY_WEB_UPDATE_PASS];
	
	ABPerson * person = [self.lastCall valueForKey:PERSON_KEY];
	
	NSString * name = [self.lastCall valueForKey:NAME_KEY];
	NSString * number = [self.lastCall valueForKey:NUMBER_KEY];
	
	if (person != nil)
	{
		name = [NSString stringWithFormat:@"%@ %@", [person valueForProperty:kABFirstNameProperty], [person valueForProperty:kABLastNameProperty]];

		if ([[person valueForProperty:kABPersonFlags] boolValue])
			name = [person valueForProperty:kABOrganizationProperty];
	}

	NSURL * cgiUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@@%@?do=upload&time=%@&caller=%@&number=%@", 
				user, pass, urlBase, 
				[[[self.lastCall valueForKey:TIME_KEY] description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
				[name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], 
				[number stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

	[[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:cgiUrl] delegate:self startImmediately:YES];
	
	self.uploadTimer = nil;
}

- (void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error
{
	NSLog (@"error = %@", error);
	
	[connection release];
}

- (void) connectionDidFinishLoading:(NSURLConnection *) connection
{
	[connection release];
}

@end
